package com.unlcn.ils.wms.backend.service.inspectApp.impl;

import cn.huiyunche.commons.exception.BusinessException;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.unlcn.ils.wms.backend.enums.DeleteFlagEnum;
import com.unlcn.ils.wms.backend.enums.TmsInsepectExcpStatusEnum;
import com.unlcn.ils.wms.backend.enums.TmsInspectStatusEnum;
import com.unlcn.ils.wms.backend.enums.WmsExcpStatusEnum;
import com.unlcn.ils.wms.backend.service.inspectApp.TmsInspectComponentMissService;
import com.unlcn.ils.wms.base.dto.TmsInspectComponentMissDTO;
import com.unlcn.ils.wms.base.dto.WmsInspectForAppDTO;
import com.unlcn.ils.wms.base.mapper.inbound.WmsInboundOrderDetailMapper;
import com.unlcn.ils.wms.base.mapper.inbound.WmsInboundOrderMapper;
import com.unlcn.ils.wms.base.mapper.inspectApp.TmsInspectComponentMissExpandMapper;
import com.unlcn.ils.wms.base.mapper.inspectApp.TmsInspectComponentMissMapper;
import com.unlcn.ils.wms.base.mapper.inspectApp.TmsInspectExcpMapper;
import com.unlcn.ils.wms.base.mapper.inspectApp.TmsInspectLogMapper;
import com.unlcn.ils.wms.base.model.inbound.WmsInboundOrder;
import com.unlcn.ils.wms.base.model.inbound.WmsInboundOrderDetail;
import com.unlcn.ils.wms.base.model.inbound.WmsInboundOrderDetailExample;
import com.unlcn.ils.wms.base.model.inspectApp.TmsInspectComponentMiss;
import com.unlcn.ils.wms.base.model.inspectApp.TmsInspectComponentMissExample;
import com.unlcn.ils.wms.base.model.inspectApp.TmsInspectExcpExample;
import com.unlcn.ils.wms.base.model.inspectApp.TmsInspectLog;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 缺件功能
 **/
@Service
public class TmsInspectComponentMissServiceImpl implements TmsInspectComponentMissService {

    private Logger logger = LoggerFactory.getLogger(TmsInspectComponentMissServiceImpl.class);

    @Autowired
    private TmsInspectComponentMissExpandMapper tmsInspectComponentMissExpandMapper;
    @Autowired
    private TmsInspectComponentMissMapper tmsInspectComponentMissMapper;
    @Autowired
    private TmsInspectExcpMapper tmsInspectExcpMapper;
    @Autowired
    private TmsInspectLogMapper tmsInspectLogMapper;
    @Autowired
    private WmsInboundOrderMapper wmsInboundOrderMapper;
    @Autowired
    private WmsInboundOrderDetailMapper wmsInboundOrderDetailMapper;


    /**
     * 获取缺件列表
     */
    @Override
    public List<TmsInspectComponentMissDTO> getComponentMissList(String vin) {
        logger.info("TmsInspectComponentMissServiceImpl.getComponentMissList param {}", vin);
        if (StringUtils.isBlank(vin)) {
            throw new BusinessException("车架号不能为空!");
        }
        List<TmsInspectComponentMissDTO> result = Lists.newArrayList();
        try {
            //正常的业务
            //查询缺件列表
            int deletedValue = DeleteFlagEnum.DELETED.getValue();
            List<TmsInspectComponentMissDTO> missComponents = tmsInspectComponentMissExpandMapper.selectMissComponent(vin, deletedValue);
            if (CollectionUtils.isNotEmpty(missComponents)) {
                for (TmsInspectComponentMissDTO missDTO : missComponents) {
                    TmsInspectComponentMissDTO componentMissDTO = new TmsInspectComponentMissDTO();
                    BeanUtils.copyProperties(missDTO, componentMissDTO);
                    componentMissDTO.setMissingStatus(true);
                    result.add(componentMissDTO);
                }
            }
            //查询非缺件列表
            List<TmsInspectComponentMissDTO> notMissComponent = tmsInspectComponentMissExpandMapper.selectNotMissComponent(vin, deletedValue);
            if (CollectionUtils.isNotEmpty(notMissComponent)) {
                for (TmsInspectComponentMissDTO componentMissDTO : notMissComponent) {
                    TmsInspectComponentMissDTO notMissDTO = new TmsInspectComponentMissDTO();
                    BeanUtils.copyProperties(componentMissDTO, notMissDTO);
                    notMissDTO.setMissingStatus(false);
                    result.add(notMissDTO);
                }
            }
            if (Objects.equals(result, null)) {
                throw new BusinessException("缺件列表暂无数据");
            }
            //按照id排序
            result.sort(Comparator.comparing(TmsInspectComponentMissDTO::getComponentId));
        } catch (Exception e) {
            logger.error("TmsInspectComponentMissServiceImpl.getComponentMissList param {}", e);
            throw new BusinessException("查询缺件列表异常!" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取缺件列表
     * <p>
     * 2018-1-20 增加维修业务重写此方法
     * 2018-5-9 缺件部件常量增加仓库code区分
     * </p>
     */
    @Override
    public List<TmsInspectComponentMissDTO> getComponentMissListNew(String vin, String whCode) {
        if (StringUtils.isBlank(vin)) {
            throw new BusinessException("车架号不能为空!");
        }
        if (StringUtils.isBlank(whCode)) {
            throw new BusinessException("仓库code不能为空!");
        }
        List<TmsInspectComponentMissDTO> result = null;
        result = Lists.newArrayList();
        HashMap<String, Object> params = Maps.newHashMap();
        params.put("notDel",DeleteFlagEnum.NORMAL.getValue());
        params.put("closeValue",WmsExcpStatusEnum.CLOSED_EXCP.getValue());
        params.put("vin",vin);
        params.put("whCode",whCode);
        List<TmsInspectComponentMissDTO> missComponents = tmsInspectComponentMissExpandMapper.selectMissComponentListNew(params);
        if (CollectionUtils.isNotEmpty(missComponents)) {
            for (TmsInspectComponentMissDTO missDTO : missComponents) {
                TmsInspectComponentMissDTO componentMissDTO = new TmsInspectComponentMissDTO();
                BeanUtils.copyProperties(missDTO, componentMissDTO);
                componentMissDTO.setMissingStatus(true);
                result.add(componentMissDTO);
            }
        }
        //查询非缺件列表
        List<TmsInspectComponentMissDTO> notMissComponent = tmsInspectComponentMissExpandMapper.selectNotMissComponentNew(params);
        if (CollectionUtils.isNotEmpty(notMissComponent)) {
            for (TmsInspectComponentMissDTO componentMissDTO : notMissComponent) {
                TmsInspectComponentMissDTO notMissDTO = new TmsInspectComponentMissDTO();
                BeanUtils.copyProperties(componentMissDTO, notMissDTO);
                notMissDTO.setMissingStatus(false);
                result.add(notMissDTO);
            }
        }
        if (Objects.equals(result, null)) {
            throw new BusinessException("缺件列表暂无数据");
        }
        //按照id排序
        result.sort(Comparator.comparing(TmsInspectComponentMissDTO::getComponentId));
        return result;
    }

    /**
     * 保存并编辑缺件列表
     * <p>
     * 2015-5-11 异常类型按照仓库code区分
     * </p>
     */
    @Override
    public void saveComponentMiss(WmsInspectForAppDTO dto) {
        logger.info("TmsInspectComponentMissServiceImpl.saveComponentMiss param {}", dto);
        if (dto == null) {
            throw new BusinessException("参数不能为空");
        }
        String whCode = dto.getWhCode();
        String missIds = dto.getMissIds();
        Long inspectId = dto.getInspectId();
        String userId = dto.getUserId();
        if (Objects.equals(inspectId, null)) {
            throw new BusinessException("验车单Id不能为空!");
        }
        if (StringUtils.isBlank(userId)) {
            throw new BusinessException("验车用户Id不能为空!");
        }
        if (StringUtils.isBlank(whCode)) {
            throw new BusinessException("仓库code不能为空!");
        }
        WmsInboundOrder inboundInspect = null;

        inboundInspect = wmsInboundOrderMapper.selectByPrimaryKey(inspectId);
        if (!Objects.equals(inboundInspect, null)) {
            if (Objects.equals(inboundInspect.getInspectStatus(), TmsInspectStatusEnum.WAYBILL_QUALIFY.getValue())) {
                throw new BusinessException("合格车辆不能进行异常标记");
            }
            if (Objects.equals(inboundInspect.getInspectStatus(), TmsInspectStatusEnum.WAYBILL_CONFIRM_EXCP.getValue())) {
                throw new BusinessException("该车辆已经验车登记,不能进行该操作");
            }
            //先判断之前是否存在该缺件异常
            TmsInspectComponentMissExample missExample = new TmsInspectComponentMissExample();
            missExample.createCriteria()
                    .andInspectIdEqualTo(inspectId)
                    .andIsDeletedEqualTo(DeleteFlagEnum.NORMAL.getValue());
            TmsInspectComponentMiss miss = new TmsInspectComponentMiss();
            miss.setGmtUpdate(new Date());
            miss.setIsDeleted(DeleteFlagEnum.DELETED.getValue());
            tmsInspectComponentMissMapper.updateByExampleSelective(miss, missExample);
            //再插入新的异常记录
            if (StringUtils.isNotBlank(missIds)) {
                String[] ids_array = missIds.split(",");
                //将缺件数据插入关联表,标记验车单为异常
                for (String missId : ids_array) {
                    //判断是否存在
                    //先删除原来的异常和图片--因维修要展示经维修并且已关闭的异常为减少判断-在进行异常标注的时候
                    // 1.先将本次要标记的异常在之前的异常记录比对，如果在以前是存在的--就将时间戳及异常类型设置为空(标记异常的时候)
                    //2.插入本次标记的异常及关联的图片
                    //3.再将原来不存在于本次标记异常类的数据并且含有时间戳的数据统一更新为当前要标注的一批的时间戳(验车登记的时候)
                    TmsInspectComponentMissExample componentMissExample = new TmsInspectComponentMissExample();
                    componentMissExample.createCriteria().andInspectIdEqualTo(inspectId)
                            .andComponentIdEqualTo(Long.parseLong(missId))
                            .andExcpTimestampIsNotNull();
                    TmsInspectComponentMiss componentMiss = new TmsInspectComponentMiss();
                    componentMiss.setGmtUpdate(new Date());
                    componentMiss.setExcpTimestamp(null);
                    componentMiss.setExcpTypeCode(null);
                    tmsInspectComponentMissMapper.updateByExampleSelective(componentMiss, componentMissExample);
                    TmsInspectComponentMiss componentMissNew = new TmsInspectComponentMiss();
                    componentMissNew.setComponentId(Long.parseLong(missId));
                    componentMissNew.setInspectId(inspectId);
                    //查询车架号
                    WmsInboundOrderDetailExample detailExample = new WmsInboundOrderDetailExample();
                    detailExample.createCriteria().andOddOdIdEqualTo(inboundInspect.getOdId());
                    List<WmsInboundOrderDetail> orderDetails = wmsInboundOrderDetailMapper.selectByExample(detailExample);
                    if (CollectionUtils.isNotEmpty(orderDetails)) {
                        componentMissNew.setInspectVin(orderDetails.get(0).getOddVin());
                    }
                    componentMissNew.setIsDeleted(DeleteFlagEnum.NORMAL.getValue());
                    componentMissNew.setGmtCreate(new Date());
                    componentMissNew.setGmtUpdate(new Date());
                    componentMissNew.setWhCode(whCode);
                    tmsInspectComponentMissMapper.insertSelective(componentMissNew);
                }
                //标记为异常
                inboundInspect.setInspectStatus(TmsInspectStatusEnum.WAYBILL_EXCP.getValue());
                inboundInspect.setGmtUpdate(new Date());
                inboundInspect.setInspectTime(new Date());
                inboundInspect.setInspectUserId(userId);
                wmsInboundOrderMapper.updateByPrimaryKeySelective(inboundInspect);
            } else {
                //检查是否还存在其他异常,没有就直接标记为合格
                TmsInspectExcpExample tmsInspectExcpExample = new TmsInspectExcpExample();
                TmsInspectExcpExample.Criteria excpExampleCriteria = tmsInspectExcpExample.createCriteria();
                excpExampleCriteria.andInspectIdEqualTo(inboundInspect.getOdId());
                excpExampleCriteria.andDelFlagNotEqualTo(false);
                excpExampleCriteria.andDealStatusEqualTo(TmsInsepectExcpStatusEnum.BILL_UNTREATED.getValue());
                int count = tmsInspectExcpMapper.countByExample(tmsInspectExcpExample);
                if (count == 0) {
                    inboundInspect.setInspectStatus(TmsInspectStatusEnum.WAYBILL_INIT.getValue());
                    inboundInspect.setOdCheckDesc(null);
                    inboundInspect.setOdCheckResult(null);
                    inboundInspect.setGmtUpdate(new Date());
                    inboundInspect.setInspectTime(new Date());
                    inboundInspect.setInspectUserId(userId);
                }
                wmsInboundOrderMapper.updateByPrimaryKeySelective(inboundInspect);
            }
        } else {
            throw new BusinessException("未查询到该订单信息!");
        }
        //插入日志
        WmsInboundOrder finalInboundInspect = inboundInspect;
        new Thread(() -> {
            TmsInspectLog log = new TmsInspectLog();
            log.setMsg("更新缺件异常成功!");
            log.setGmtCreate(new Date());
            log.setGmtUpdate(new Date());
            log.setInspectId(finalInboundInspect.getOdId());
            log.setUserId(userId);
            tmsInspectLogMapper.insertSelective(log);
        }).start();
    }

    /**
     * 获取缺件列表名
     */
    @Override
    public String getMissComponentNames(String vin) {
        logger.info("TmsInspectComponentMissServiceImpl.getMissComponentNames param {}", vin);
        //查询缺件列表
        int deletedValue = DeleteFlagEnum.DELETED.getValue();
        List<TmsInspectComponentMissDTO> missComponents = tmsInspectComponentMissExpandMapper.selectMissComponent(vin, deletedValue);
        StringBuilder sb = new StringBuilder();
        if (!Objects.equals(missComponents, null)) {
            missComponents.forEach(v -> {
                sb.append(v.getComponentName()).append(",");
            });
        }
        if (StringUtils.isNotBlank(sb)) {
            return sb.substring(0, sb.length() - 1);
        }
        return null;
    }

    /**
     * 获取缺件列表名--维修需求复写方法
     * <p>
     * 2018-5-10  缺件列表区分仓库code
     * </p>
     */
    @Override
    public String getMissComponentNamesNew(Long inspectId, String whCode) {
        logger.info("TmsInspectComponentMissServiceImpl.getMissComponentNamesNew param {}", inspectId);
        //查询缺件列表
        int deletedValue = DeleteFlagEnum.DELETED.getValue();
        List<TmsInspectComponentMissDTO> missComponents = tmsInspectComponentMissExpandMapper.selectMissComponentNew(inspectId, deletedValue);
        StringBuilder sb = new StringBuilder();
        if (!Objects.equals(missComponents, null)) {
            missComponents.forEach(v -> {
                sb.append(v.getComponentName()).append(",");
            });
        }
        if (StringUtils.isNotBlank(sb)) {
            return sb.substring(0, sb.length() - 1);
        }
        return null;
    }

    /**
     * 统计缺件的异常数量
     */
    public Integer getMissComponentCount(String vin) {
        logger.info("TmsInspectComponentMissServiceImpl.getMissComponentCount param {}", vin);
        if (StringUtils.isBlank(vin)) {
            throw new BusinessException("车架号不能为空!");
        }
        TmsInspectComponentMissExample missExample = new TmsInspectComponentMissExample();
        TmsInspectComponentMissExample.Criteria criteria = missExample.createCriteria();
        criteria.andInspectVinEqualTo(vin);
        return tmsInspectComponentMissMapper.countByExample(missExample);
    }
}
